package com.ruoyi.mall.app.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mall.app.domain.DtsBrands;
import com.ruoyi.mall.app.domain.DtsCart;
import com.ruoyi.mall.app.service.DtsCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;


@RestController
@RequestMapping("/api/shopping/cart")
public class DtsCartController {
    @Autowired
    private DtsCartService dtsCartService;

    @GetMapping("/list")
    public AjaxResult list(DtsCart dtsCart)
    {
        List<DtsBrands> list = dtsCartService.selectCartBrands(dtsCart);
        if (list != null){
            return success(list);
        }else {
            return error();
        }
    }

    @GetMapping("/update")
    public AjaxResult updata(Long id,Long number)
    {
        return success(dtsCartService.updateCartByUserId(id,number));
    }

    @Log(title = "批量删除商品", businessType = BusinessType.INSERT)
    @GetMapping("/deletes")
    @DeleteMapping("/{ids}")
    public AjaxResult deletes(String ids) throws UnsupportedEncodingException, JsonProcessingException {
        String decodedData = URLDecoder.decode(ids, StandardCharsets.UTF_8.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        // 将 JSON 字符串转换为 List，根据实际元素类型调整
        Long[] arr = objectMapper.readValue(decodedData, Long[].class);
        return success(dtsCartService.deleteCartByUserIds(arr));
    }

    @GetMapping("/addCart")
    public AjaxResult addCart(DtsCart dtsCart) throws UnsupportedEncodingException {
        dtsCart.setGoodsName(URLDecoder.decode(dtsCart.getGoodsName(), StandardCharsets.UTF_8.toString()));
        dtsCart.setSpecifications(URLDecoder.decode(dtsCart.getSpecifications(), StandardCharsets.UTF_8.toString()));
        dtsCart.setPicUrl(URLDecoder.decode(dtsCart.getPicUrl(), StandardCharsets.UTF_8.toString()));
        return success(dtsCartService.addCart(dtsCart));
    }
}
